//
//  ZCproblemVC.m
//  zctx
//
//  Created by apple on 16/1/21.
//  Copyright © 2016年 sanliang. All rights reserved.
//

#import "ZCproblemVC.h"
#import "CLTree.h"
#import "ZCLoginVC.h"
#import "HcCustomKeyboard.h"
#import "RCViewCell.h"
@interface ZCproblemVC ()<UITableViewDataSource,UITableViewDelegate,HcCustomKeyboardDelegate>
@property(strong,nonatomic) NSMutableArray* dataArray; //保存全部数据的数组
@property (nonatomic,strong)NSArray *requestArray;
@property(strong,nonatomic) NSArray *displayArray;   //保存要显示在界面上的数据的数组

@property (nonatomic,assign)NSInteger offset;

@end

@implementation ZCproblemVC

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"ZCproblemVC"];
    [MTA trackPageViewBegin:@"ZCproblemVC"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"ZCproblemVC"];
    [MTA trackPageViewEnd:@"ZCproblemVC"];
}

-(void)updateRequest{
    if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus >0) {
        self.bannerView.hidden = YES;
    }
    [self requestData:YES];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    //AF 开启监听网络状态
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    _offset = 0;
    self.dataArray = [[NSMutableArray alloc]init];
    self.requestArray = [[NSArray alloc]init];
    self.displayArray = [[NSArray alloc]init];
    
    _myTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:_myTableView];
    [_myTableView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    _myTableView.sectionHeaderHeight = 0.0001;
    _myTableView.dataSource = self;
    _myTableView.delegate = self;
    _myTableView.backgroundColor = [UIColor colorWithHexString:@"#fafcfb"];
    _myTableView.separatorColor = RGB(236, 237, 238);
    
    [self requestData:YES];
    _myTableView.mj_header = [MJDIYHeader headerWithRefreshingBlock:^{
        _offset = 0;
        [_dataArray removeAllObjects];
        [self requestData:NO];//广告
    }];
    [_myTableView registerNib:[UINib nibWithNibName:@"Level1_Cell" bundle:nil] forCellReuseIdentifier:@"level1cell"];
    
//    CLTreeView_LEVEL1_Cell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier1];
//    if(cell == nil){
//        cell = [[[NSBundle mainBundle] loadNibNamed:@"Level1_Cell" owner:self options:nil] lastObject];
//    }
//    _myTableView.mj_footer = [MJDIYFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
}
#pragma mark 加载更多
-(void)loadMoreData{
    //上拉加载
    _offset = _offset+1;
//    [self requestData];
}

-(void)requestData:(BOOL)animation{
    if (animation) {
        [GMDCircleLoader setOnView:self.view withTitle:@"努力加载中..." animated:YES];
    }
    [NetworkManager requestIndexgetfaqlistWithsuccess:^(NSDictionary *dictResponse) {
        [GMDCircleLoader hideFromView:self.view animated:YES];
        [_myTableView.mj_header endRefreshing];
        if ([[dictResponse objectForKey:@"content"] isKindOfClass:[NSArray class]]){
            NSArray *sarray = (NSArray *)[dictResponse objectForKey:@"content"];
            if (sarray.count>0) {
                self.requestArray = [sarray copy];
                [self addTestData];//添加演示数据
                [self reloadDataForDisplayArray];//初始化将要显示的数据
            }
        }
    } failure:^(NSError *error) {
        [_myTableView.mj_header endRefreshing];
        [GMDCircleLoader hideFromView:self.view animated:YES];
        self.bannerView.hidden = NO;
    }];
}

//添加演示数据
-(void) addTestData{
    
    for (int  i=0; i< self.requestArray.count; i++) {
        NSDictionary *dict = (NSDictionary *)self.requestArray[i];
        NSString *title = [NSString stringWithFormat:@"%@",[dict objectForKey:@"title"]];
        NSString *content = [NSString stringWithFormat:@"%@",[dict objectForKey:@"content"]];
        CLTreeViewNode *node3 = [[CLTreeViewNode alloc]init];
        node3.nodeLevel = 0;//根层cell
        node3.type = 1;//type 1的cell
        node3.sonNodes = nil;
        node3.isExpanded = NO;//关闭状态
        CLTreeView_LEVEL1_Model *tmp3 =[[CLTreeView_LEVEL1_Model alloc]init];
        tmp3.name = title;
        node3.nodeData = tmp3;

        CLTreeViewNode *node5 = [[CLTreeViewNode alloc]init];
        node5.nodeLevel = 1;//第一层节点
        node5.type = 2;//type 2的cell
        node5.sonNodes = nil;
        node5.isExpanded = NO;
        CLTreeView_LEVEL2_Model *tmp5 =[[CLTreeView_LEVEL2_Model alloc]init];
        tmp5.signture = content;
        node5.nodeData = tmp5;

        node3.sonNodes = [NSMutableArray arrayWithObjects:node5,nil];//插入子节点
        [_dataArray addObject:node3];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger) tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{
    return _displayArray.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *indentifier = @"level0cell";
    static NSString *indentifier1 = @"level1cell";
    static NSString *indentifier2 = @"level2cell";
    CLTreeViewNode *node = [_displayArray objectAtIndex:indexPath.row];
    
    if(node.type == 0){//类型为0的cell
        CLTreeView_LEVEL0_Cell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
        if(cell == nil){
            cell = [[[NSBundle mainBundle] loadNibNamed:@"Level0_Cell" owner:self options:nil] lastObject];
        }
        cell.node = node;
        [self loadDataForTreeViewCell:cell with:node];//重新给cell装载数据
        [cell setNeedsDisplay]; //重新描绘cell
        return cell;
    }
    else if(node.type == 1){//类型为1的cell
        CLTreeView_LEVEL1_Cell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier1];
        if(cell == nil){
            cell = [[CLTreeView_LEVEL1_Cell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier1];
        }
        cell.node = node;
        [self loadDataForTreeViewCell:cell with:node];
//        [cell setNeedsDisplay];
        return cell;
    }
    else{//类型为2的cell
        CLTreeView_LEVEL2_Cell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier2];
        if(cell == nil){
            cell = [[[NSBundle mainBundle] loadNibNamed:@"Level2_Cell" owner:self options:nil] lastObject];
        }
        cell.node = node;
        [self loadDataForTreeViewCell:cell with:node];
        [cell setNeedsDisplay];
        return cell;
    }
}

/*---------------------------------------
 为不同类型cell填充数据
 --------------------------------------- */
-(void) loadDataForTreeViewCell:(UITableViewCell*)cell with:(CLTreeViewNode*)node{
    if(node.type == 0){
        CLTreeView_LEVEL0_Model *nodeData = node.nodeData;
        ((CLTreeView_LEVEL0_Cell*)cell).name.text = nodeData.name;
        if(nodeData.headImgPath != nil){
            //本地图片
            [((CLTreeView_LEVEL0_Cell*)cell).imageView setImage:[UIImage imageNamed:nodeData.headImgPath]];
        }
        else if (nodeData.headImgUrl != nil){
            //加载图片，这里是同步操作。建议使用SDWebImage异步加载图片
            [((CLTreeView_LEVEL0_Cell*)cell).imageView setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:nodeData.headImgUrl]]];
        }
    }
    
    else if(node.type == 1){
        CLTreeView_LEVEL1_Model *nodeData = node.nodeData;
        ((CLTreeView_LEVEL1_Cell*)cell).name.text = nodeData.name;
        ((CLTreeView_LEVEL1_Cell*)cell).sonCount.text = nodeData.sonCnt;
    }
    
    else{
        CLTreeView_LEVEL2_Model *nodeData = node.nodeData;
        ((CLTreeView_LEVEL2_Cell*)cell).name.text = nodeData.name;
        ((CLTreeView_LEVEL2_Cell*)cell).signture.text = nodeData.signture;
//        if(nodeData.headImgPath != nil){
//            //本地图片
//            [((CLTreeView_LEVEL2_Cell*)cell).headImg setImage:[UIImage imageNamed:nodeData.headImgPath]];
//        }
//        else if (nodeData.headImgUrl != nil){
//            //加载图片，这里是同步操作。建议使用SDWebImage异步加载图片
//            [((CLTreeView_LEVEL2_Cell*)cell).headImg setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:nodeData.headImgUrl]]];
//        }
    }
}

/*---------------------------------------
 cell高度默认为50
 --------------------------------------- */
-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    CLTreeViewNode *node = [_displayArray objectAtIndex:indexPath.row];
    if (node.type ==2) {
        CLTreeView_LEVEL2_Model *nodeData = node.nodeData;
//        CLTreeView_LEVEL2_Cell *cell = (CLTreeView_LEVEL2_Cell*)[tableView cellForRowAtIndexPath:indexPath];
        
        CGSize size = CGSizeMake(SCREEN_WIDTH-39-25,2000); //设置一个行高上限
        NSDictionary *attribute = @{NSFontAttributeName:[UIFont systemFontOfSize:13]};
        CGFloat height = [nodeData.signture boundingRectWithSize:size options: NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin| NSStringDrawingUsesFontLeading attributes:attribute context:nil].size.height;
        if (height<=22) {
            return 44;
        }else{
            return height+21;
        }
    }else{
        return 44;
    }
}

/*---------------------------------------
 处理cell选中事件，需要自定义的部分
 --------------------------------------- */
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self reloadDataForDisplayArrayChangeAt:indexPath.row];//修改cell的状态(关闭或打开)

    CLTreeViewNode *node = [_displayArray objectAtIndex:indexPath.row];

    if(node.type == 2){
        //处理叶子节点选中，此处需要自定义
    }
    else{
        CLTreeView_LEVEL1_Cell *cell = (CLTreeView_LEVEL1_Cell*)[_myTableView cellForRowAtIndexPath:indexPath];
        if(node.isExpanded ){
            cell.arrowView.image = [UIImage imageNamed:@"accessory_shang"];
//            [self rotateArrow:cell with:M_PI/2];
        }
        else{
            cell.arrowView.image = [UIImage imageNamed:@"accessory_xia"];
//            [self rotateArrow:cell with:0];
        }
    }
    
}

/*---------------------------------------
 旋转箭头图标
 --------------------------------------- */
-(void) rotateArrow:(CLTreeView_LEVEL1_Cell*) cell with:(double)degree{
    [UIView animateWithDuration:0.35 delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        cell.arrowView.layer.transform = CATransform3DMakeRotation(degree, 0, 0, 1);

    } completion:NULL];

}

/*---------------------------------------
 初始化将要显示的cell的数据
 --------------------------------------- */
-(void) reloadDataForDisplayArray{
    NSMutableArray *tmp = [[NSMutableArray alloc]init];
    for (CLTreeViewNode *node in _dataArray) {
        [tmp addObject:node];
        if(node.isExpanded){
            for(CLTreeViewNode *node2 in node.sonNodes){
                [tmp addObject:node2];
//                if(node2.isExpanded){
//                    for(CLTreeViewNode *node3 in node2.sonNodes){
//                        [tmp addObject:node3];
//                    }
//                }
            }
        }
    }
    _displayArray = [NSArray arrayWithArray:tmp];
    [self.myTableView reloadData];
}

/*---------------------------------------
 修改cell的状态(关闭或打开)
 --------------------------------------- */
-(void) reloadDataForDisplayArrayChangeAt:(NSInteger)row{
    
    NSMutableArray *tmp = [[NSMutableArray alloc]init];
    NSInteger cnt=0;
    for (CLTreeViewNode *node in _dataArray) {
        [tmp addObject:node];
        if(cnt == row){
            node.isExpanded = !node.isExpanded;
        }
        ++cnt;
        if(node.isExpanded){
            for(CLTreeViewNode *node2 in node.sonNodes){
                [tmp addObject:node2];
                if(cnt == row){
                    node2.isExpanded = !node2.isExpanded;
                }
                ++cnt;
                if(node2.isExpanded){
                    for(CLTreeViewNode *node3 in node2.sonNodes){
                        [tmp addObject:node3];
                        ++cnt;
                    }
                }
            }
        }
    }
    _displayArray = [NSArray arrayWithArray:tmp];
    [self.myTableView reloadData];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (_displayArray.count>0) {
        return 80;
    }else{
        return 0.001;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView *footerView = [[UIView alloc]init];
    if (_displayArray.count>0) {
        footerView.frame = CGRectMake(0, 0, SCREEN_WIDTH,80);
        UIButton *helpButton = [[UIButton alloc]init];
        [footerView addSubview:helpButton];
        [helpButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(footerView.centerX).with.offset(0);
            make.centerY.equalTo(footerView.centerY).with.offset(0);
            make.width.mas_equalTo(200);
            make.height.mas_equalTo(50);
        }];
        helpButton.titleLabel.font = [UIFont systemFontOfSize:16];
        helpButton.backgroundColor = [UIColor clearColor];
        [helpButton setTitle:@"我想问一下..." forState:UIControlStateNormal];
        [helpButton setTitleColor:MainColor forState:UIControlStateNormal];
        [helpButton addTarget:self action:@selector(Clickask) forControlEvents:UIControlEventTouchUpInside];
        return footerView;
    }else{
        return footerView;
    }
}



#pragma mark 我想问一下
-(void)Clickask{
    if (UserModel.password.length>1) {
        [[HcCustomKeyboard customKeyboard]textViewShowView:self customKeyboardDelegate:self andType:HcCustomKeyboardTypeBtton andplaceholder:@"我想问一下"];
    }else{
        ZCLoginVC *loginVC = [[ZCLoginVC alloc]init];
        loginVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}

-(void)talkBtnClick:(UITextView *)textViewGet{
    
}

@end
